package mygang.helper;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import mygang.model.BaseModel;
import mygang.model.Option;
import mygang.model.OptionInterface;
import org.apache.log4j.Logger;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 * date: 15/12/2012
 */
public class Utils extends BaseModel {
    
    private static final Logger log = Logger.getLogger(Utils.class.toString());
    
    public static <M extends OptionInterface> List<Option>  convertToOptions(List<M> list){
        List<Option> result = new ArrayList<Option>();
        for(OptionInterface element : list){
            result.add(element.toOption());
        }
        return result;
    }
    
    public static Properties readProps(String filename){
        Properties props = new Properties();
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            //loading properites from properties file
            props.load(classLoader.getResourceAsStream(filename));
        } catch (IOException ex) {
            log.debug(ex.getMessage());
            ex.printStackTrace();
        }
        return props;
    }
    
    /**
     * Returns representation of object as {@link String}
     * @param obj defines object to conversion
     * @return representation of object as {@link String}
     */
    public static String toString(Object obj){
        String separator = ", ";
        
        StringBuilder result = new StringBuilder();
        result.append(obj.getClass().getName());
        result.append(" {");
        
        Field[] fields = obj.getClass().getDeclaredFields();
        for(int i=0; i < fields.length; i++){
            try {
                Field field = fields[i];
                field.setAccessible(true); // You might want to set modifier to public first.
                Object value = field.get(obj); 
                result.append(field.getName()+ " = " + value);
                if(i+1 != fields.length) result.append(separator);
            } catch (IllegalArgumentException ex) {
                log.debug(ex.getMessage());
            } catch (IllegalAccessException ex) {
                log.debug(ex.getMessage());
            }
        }
        
        result.append("}");
        return result.toString();
    }
}